//
//  ShinnyHollywoodGalleryController.m
//  Gallery
//
//  Created by Dario Lencina on 6/24/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ShinnyHollywoodGalleryController.h"
#import "UIImageExtras.h"
#import "DarioSharedPreprocessorDirectives.h"
#import <QuartzCore/QuartzCore.h>

#define kSizeOfThumbnail 75
#define kOffsetOfThumbs 4
#define kwidthOfDetailImageContainer 264
#define kheightOfDetailImageContainer 224
#define kscaleOfDetailImageContainer 1.15
#define kSelectedButtonZoom 1.15

#define ShinnyHollywoodGalleryOrientationVertical @"0"
#define ShinnyHollywoodGalleryOrientationHorizontal @"1"
#define ShinnyHollywoodGalleryOrientationUnknown @"2"

@implementation ShinnyHollywoodGalleryController
@synthesize images;
@synthesize thumbs, scrollView;
@synthesize selectedImage, detailImageContainer;

#pragma mark -
#pragma mark Initialization

- (id) init {
	if ((self = [super init])) {
		images =  [NSMutableArray new];
		thumbs =  [NSMutableArray new];
		[self setDetailImageContainer:nil];
		_currentOrientation= ShinnyHollywoodGalleryOrientationUnknown;
		cachedImageTag=NSIntegerMax;
	}
	return self;
}

- (void)viewDidLoad {
	detailImageContainer= [[ShinnyHollywoodGalleryDetailImageViewer alloc] initWithFrame:CGRectMake(0, 0, 250, kheightOfDetailImageContainer)];
	[self.view addSubview:detailImageContainer];
	detailImageContainer.center= CGPointMake(self.view.center.x, self.view.center.y-60);
	[detailImageContainer setHidden:TRUE];
	[detailImageContainer setDelegate:self];
	[scrollView setShowsHorizontalScrollIndicator:FALSE];
	[scrollView setShowsVerticalScrollIndicator:FALSE];	
	[scrollView setOpaque:TRUE];
	[super viewDidLoad];
	[self.navigationController setToolbarHidden:FALSE animated:FALSE];
//	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)
//												 name:UIDeviceOrientationDidChangeNotification object:nil];
}



//-(void)orientationChanged:(NSNotification *)notification{
//	if(UIInterfaceOrientationIsLandscape([[notification object] orientation])){
//		if([detailImageContainer isHidden]){
//			cachedImageTag=0;
//			self.selectedImage=[images objectAtIndex:cachedImageTag];
//			for(UIView * button in [scrollView subviews]){
//				if (button.tag==cachedImageTag) {
//					[self setButtonSelected:button];
//				}
//			}
//			[detailImageContainer setFrontImageProperty:selectedImage animated:TRUE];
//			[detailImageContainer setHidden:FALSE];
//			[self resizeScrollToGivenOrientation:ShinnyHollywoodGalleryOrientationHorizontal];
//		}
//		[self.navigationController setNavigationBarHidden:TRUE animated: TRUE];
//		[self.navigationController setToolbarHidden:TRUE animated: TRUE];
//		if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 3.2) {
//			[[UIApplication sharedApplication] setStatusBarHidden:TRUE withAnimation: UIStatusBarAnimationSlide];
//		}else {
//			[[UIApplication sharedApplication] setStatusBarHidden:TRUE animated: TRUE];
//		}
//		[detailImageContainer.layer setTransform:CATransform3DScale(CATransform3DMakeRotation(M_PI/2, 0, 0, 1), 1.3, 1.3, 1.3) ];
//	}else{
//		if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 3.2) {
//			[[UIApplication sharedApplication] setStatusBarHidden:FALSE withAnimation: UIStatusBarAnimationSlide];
//		}else {
//			[[UIApplication sharedApplication] setStatusBarHidden:FALSE animated: TRUE];
//		}
//		[self.navigationController setNavigationBarHidden:FALSE animated: TRUE];
//		[self.navigationController setToolbarHidden:FALSE animated: TRUE];
//		[detailImageContainer.layer setTransform:CATransform3DIdentity];
//	}
//	   
//}


-(void)viewDidAppear:(BOOL)animated{
	static BOOL mustResizeScrollToVertical= TRUE;
	if(mustResizeScrollToVertical){
	[self resizeScrollToVertical];
		mustResizeScrollToVertical= FALSE;
	}
}

-(void) viewDidUnload{
	[detailImageContainer release];
}

-(void)setControllerImagesWithArray:(NSArray *)array{
	for(UIImage * image in array){
		[self addImage:image];
	}
}

- (void)addImage:(UIImage *)image {
	@synchronized(self){
		[images addObject:image];
		UIImage * scaledImage= [image imageByScalingAndCroppingForSize:CGSizeMake(kSizeOfThumbnail, kSizeOfThumbnail)];
		[thumbs addObject:scaledImage];
	}
}

#pragma mark -
#pragma mark Animated Resize

-(void)resizeScrollToVertical{
	int row = 0;
	int column = 0;
	int offsetx=kOffsetOfThumbs;
	int offsety=kOffsetOfThumbs;
	
	[UIView beginAnimations:@"agregarImagen" context:nil];
	[UIView setAnimationDuration:[[UIApplication sharedApplication] statusBarOrientationAnimationDuration]];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	
	if([scrollView.subviews count]>3){
		for(int i = 0; i < [scrollView.subviews count]; ++i) {
			UIView * subview= [scrollView.subviews objectAtIndex:i];
			if (![subview isMemberOfClass:[UIButton class]]) 
				continue;

			subview.frame = CGRectMake(offsetx,offsety, kSizeOfThumbnail, kSizeOfThumbnail);
			offsetx+= kSizeOfThumbnail + 4;
			if (column == 3) {
				column = 0;
				offsetx=kOffsetOfThumbs;
				offsety+=kSizeOfThumbnail + kOffsetOfThumbs;
				row++;
			} else {
				column++;
			}
		}
	}else{
		for(int i = 0; i < thumbs.count; ++i) {
			UIImage *thumb = [thumbs objectAtIndex:i];
			UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
			[button setOpaque:TRUE];
			button.frame = CGRectMake(offsetx,offsety, kSizeOfThumbnail, kSizeOfThumbnail);
			offsetx+= kSizeOfThumbnail + 4;
			[button setImage:thumb forState:UIControlStateNormal];
			[button addTarget:self 
					   action:@selector(buttonClicked:) 
			 forControlEvents:UIControlEventTouchDown];
			button.tag = i; 
			[scrollView addSubview:button];
			if (column == 3) {
				column = 0;
				offsetx=kOffsetOfThumbs;
				offsety+=kSizeOfThumbnail + kOffsetOfThumbs;
				row++;
			} else {
				column++;
		}
		}
	}
	[UIView commitAnimations];
	[scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, (row+1) * 80 + 10)];
}

-(void)resizeScrollToGivenOrientation:(NSString *)orientation{
	if([orientation isEqualToString:_currentOrientation])
		return;
	else
		_currentOrientation=orientation;
	
	[UIView beginAnimations:(NSString *)orientation context:nil];
	[UIView setAnimationDuration:[[UIApplication sharedApplication] statusBarOrientationAnimationDuration]];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animationDidStop: finished: context:)];
	[scrollView scrollRectToVisible:CGRectMake(0, 0, 320, 100) animated:FALSE];	
	for(UIView * theSubview in scrollView.subviews){
		if (![theSubview isMemberOfClass:[UIButton class]])
			continue;

		if ([orientation isEqualToString:ShinnyHollywoodGalleryOrientationHorizontal]) {
			theSubview.frame = CGRectMake(4,self.view.frame.size.height-kSizeOfThumbnail - kOffsetOfThumbs * 1.1, kSizeOfThumbnail, kSizeOfThumbnail);
		}
		
		if ([orientation isEqualToString:ShinnyHollywoodGalleryOrientationVertical]) {
			theSubview.frame = CGRectMake(self.view.center.x - kSizeOfThumbnail/2,self.view.center.y - kSizeOfThumbnail/2, kSizeOfThumbnail, kSizeOfThumbnail);
		}
		
	}
	[UIView commitAnimations];
}

-(void)resizeScrollToHorizontal{
	int column = 0;
	int offsetx=kOffsetOfThumbs;
	int offsety=self.view.frame.size.height-kSizeOfThumbnail - kOffsetOfThumbs * kSelectedButtonZoom;
	if([scrollView.subviews count]>1){
		for(int i = 0; i < [scrollView.subviews count]; ++i) {
			UIView * subview= [scrollView.subviews objectAtIndex:i];
			if (![subview isMemberOfClass:[UIButton class]])
				continue;

			[UIView beginAnimations:@"agregarImagen" context:nil];
			[UIView setAnimationDuration:[[UIApplication sharedApplication] statusBarOrientationAnimationDuration]];
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			subview.frame = CGRectMake(offsetx,offsety, kSizeOfThumbnail, kSizeOfThumbnail);
			offsetx+= kSizeOfThumbnail + kOffsetOfThumbs;
			[UIView commitAnimations];
			column++;
		}
	}
	else
	for(int i = 0; i < thumbs.count; ++i) {
		UIImage *thumb = [thumbs objectAtIndex:i];
		UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
		[UIView beginAnimations:@"agregarImagen" context:nil];
		[UIView setAnimationDuration:[[UIApplication sharedApplication] statusBarOrientationAnimationDuration]];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		button.frame = CGRectMake(offsetx,offsety, kSizeOfThumbnail, kSizeOfThumbnail);
		offsetx+= kSizeOfThumbnail + kOffsetOfThumbs;
		[button setImage:thumb forState:UIControlStateNormal];
		[button addTarget:self 
				   action:@selector(buttonClicked:) 
		 forControlEvents:UIControlEventTouchUpInside];
		button.tag = i; 
		[scrollView addSubview:button];
		[UIView commitAnimations];
		column++;
	}
	[scrollView setContentSize:CGSizeMake(offsetx,100)];
}

#pragma mark AnimationDelegate

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
	[UIView setAnimationDelegate:nil];
	if (![finished boolValue])
		return;
	
	if ([animationID isEqualToString:ShinnyHollywoodGalleryOrientationHorizontal]) {
		[self resizeScrollToHorizontal];
		[detailImageContainer setHidden:FALSE];
	}
		 
	if ([animationID isEqualToString:ShinnyHollywoodGalleryOrientationVertical]) {
		[self resizeScrollToVertical];
	}
	
}

#pragma mark -
#pragma mark Actions

-(void)closeButtonPressed:(UIButton *)buttonPressed inShinnyHollywoodGalleryDetailImageViewer:(ShinnyHollywoodGalleryDetailImageViewer *)viewer{
	[detailImageContainer setHidden:TRUE];
	[self setButtonSelected:nil];
	cachedImageTag=NSIntegerMax;
}

-(void)setButtonSelected:(UIButton *)button{
	[UIView beginAnimations:@"setButtonSelected" context:button];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:0.080];
	for(UIView * view in [scrollView subviews]) {
//		if(![view isMemberOfClass:[UIButton class]])
//			continue;
		if ([view isEqual:button]) {
			[view.layer setTransform:CATransform3DMakeScale(kSelectedButtonZoom, kSelectedButtonZoom, 1)];
		//	[scrollView bringSubviewToFront:view];
		}else {
			[view.layer setTransform:CATransform3DIdentity];
		//	[scrollView sendSubviewToBack:view];
		}
	}
	 

//	NSLog(@"Transform button m11 %f, m12 %f, m13 %f, m14 %f,\n m21 %f, m22 %f, m23 %f, m24 %f,\n m31 %f, m32 %f, m33 %f, m34 %f, m41 %f, m42 %f, m43 %f, m44 %f", 	button.layer.transform.m11, 	button.layer.transform.m12, 	button.layer.transform.m13, button.layer.transform.m14, button.layer.transform.m21, button.layer.transform.m22, button.layer.transform.m23, button.layer.transform.m24, button.layer.transform.m31, button.layer.transform.m32, button.layer.transform.m33, button.layer.transform.m34, button.layer.transform.m41, button.layer.transform.m42, button.layer.transform.m43, button.layer.transform.m44);
	
	
	[UIView commitAnimations];
}

-(void)needsNextImageInShinnyHollywoodGalleryDetailImageViewer:(ShinnyHollywoodGalleryDetailImageViewer *)viewer{
	if (cachedImageTag>=[images count]-1) {
		cachedImageTag=0;
	}else {
		cachedImageTag++;
	}

	self.selectedImage=[images objectAtIndex:cachedImageTag];
	for(UIView * button in [scrollView subviews]){
		if (button.tag==cachedImageTag) {
			[self setButtonSelected:(UIButton *)button];
		}
	}
	[detailImageContainer pushImage:self.selectedImage from:kCATransitionFromRight];

}

-(void)needsPreviousImageInShinnyHollywoodGalleryDetailImageViewer:(ShinnyHollywoodGalleryDetailImageViewer *)viewer{
	if (cachedImageTag<=0) {
		cachedImageTag=[images count]-1;
	}else {
		cachedImageTag--;
	}
	
	self.selectedImage=[images objectAtIndex:cachedImageTag];
	for(UIView * button in [scrollView subviews]){
		if (button.tag==cachedImageTag) {
			[self setButtonSelected:(UIButton *)button];
		}
	}
	[detailImageContainer pushImage:self.selectedImage from:kCATransitionFromLeft];	
}

- (IBAction)buttonClicked:(UIButton *)button {	
	self.selectedImage = [images objectAtIndex:button.tag];

	[self setButtonSelected:button];
	if (button.tag==cachedImageTag ) {
		
		return;
	}
	cachedImageTag=button.tag;

	if (![detailImageContainer isHidden]) {
		[detailImageContainer setFrontImageProperty:selectedImage animated:TRUE];		
	}else {
		[detailImageContainer setFrontImageProperty:selectedImage animated:FALSE];
	}
	[self resizeScrollToGivenOrientation:ShinnyHollywoodGalleryOrientationHorizontal];
	
}

-(void)animationEndedInShinnyHollywoodGalleryDetailImageViewer:(ShinnyHollywoodGalleryDetailImageViewer *)viewer{
	if([viewer isHidden]){
		[self resizeScrollToGivenOrientation:ShinnyHollywoodGalleryOrientationVertical];
		self.selectedImage=nil;
	}
}

#pragma mark -
#pragma mark Memory cleanning


- (void)dealloc {
	for(UIView * theSubview in scrollView.subviews)
		[theSubview removeFromSuperview];

	_currentOrientation=nil;	
	
	if(detailImageContainer)
		[detailImageContainer removeFromSuperview];
	
	[scrollView release];
	if(selectedImage)
	[selectedImage release];
	
	[images release];
	[thumbs release];
	[super dealloc];
}

@end
